package com.ygxsk.carhome.ui.property;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ListView;

import androidx.annotation.NonNull;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.gyf.immersionbar.ImmersionBar;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.listener.ErrorParentExtraSingle;
import com.ygxsk.carhome.response.TimeLineModel;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.ui.adapter.OrderProgrAdapter;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.integrated.retrofit.Parameterkey;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/*
 * @Author:itchenqi175@163.com
 * @Time:2023/12/28  22:06
 * @Description: 查看报修进度内容
 */
public class RepairProgressTwoActivity extends ErrorActivity implements ErrorParentExtraSingle {

    @BindView(R.id.refreshLayoutinpro)
    SmartRefreshLayout refreshLayoutinProgress;

    @BindView(R.id.recyclerViewinpro)
    ListView mRecyclerView;

    private String messageNull = "暂无报修进度~";

    /**
     * 用于上传的idpass内容
     */
    private String repairIdPass;

    //添加时间轴实体类
    private List<TimeLineModel> mDataList = new ArrayList<>();

    private OrderProgrAdapter mTimeLineAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mActivityInstance = this;

        processExtraData();

        initloading();

        initViews();

        gainDatas();

    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_repair_progresstwo;
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();
    }

    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

        toolbarHelper.setTitle(getString(R.string.title_repair_step));
        toolbarHelper.setVersionName(true, AppUtils.getAppVersionName());
        toolbarHelper.setLayoutClose(false, "", null);
        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //搜索客户信息，优先关闭软键盘
                KeyboardUtils.hideSoftInput(mActivityInstance);
                methodBack();
            }
        });

        //这里右上角没有东西的
        toolbarHelper.setLayoutRight(true, 0, "", null);

    }

    @Override
    protected void onClickNodata(View v) {

        gainDatas();

    }

    @Override
    protected void initViews() {

        //setDataListItems();
//        refreshLayoutinProgress = (SmartRefreshLayout) findViewById(R.id.refreshLayoutinpro);

        //initdatas
//        mRecyclerView = (ListView) findViewById(R.id.recyclerViewinpro);
        //mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        //mRecyclerView.setHasFixedSize(true);
        //mTimeLineAdapter = new TimeLineAdapter(mDataList);
        //mRecyclerView.setAdapter(mTimeLineAdapter);

        if (refreshLayoutinProgress != null) {

            refreshLayoutinProgress.setOnRefreshListener(new OnRefreshListener() {
                @Override
                public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                    refreshLayout.getLayout().post(new Runnable() {
                        @Override
                        public void run() {
                            gainDatas();
                            refreshLayout.finishRefresh();
                        }
                    });

                }
            });

        }

    }

    @Override
    protected void gainDatas() {

        if (NetworkUtils.isConnected()) {

            if (mDataList != null && !mDataList.isEmpty()) {
                mDataList.clear();
            }

            getServerDatas(repairIdPass);

        } else {
            netWorkError();
        }

    }

    private void getServerDatas(String repairIdPass) {

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());
        map.put(Parameterkey.repairId, repairIdPass);

//        map.put(Parameterkey.pagination, pagination_upLoad);//传递的页码
//        map.put(Parameterkey.pageSize, Parameterkey.pageSize_default);//,搜索关键字

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETREPAIRLOGBYID_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getRepairLogById_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        //
        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getRepairLogById(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                .compose(RepairProgressTwoActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<ArrayList<TimeLineModel>>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                        methodNotSuccessData(what_method, serverCode, serverMessage);
                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {

//                        CommUtils.checkMaterialDialog(materialDialog);
                        method_create_materialDialog(mActivityInstance, ConstantSign.TIPS_LOADING);

                        loadingGone();

                    }
                }).subscribe(new Consumer<ArrayList<TimeLineModel>>() {
                    @Override
                    public void accept(ArrayList<TimeLineModel> timeLineModelArrayList) throws Throwable {

                        CommUtils.checkMaterialDialog(materialDialog);

                        if (mDataList != null && !mDataList.isEmpty()) {
                            mDataList.clear();
                        }

                        if (timeLineModelArrayList != null && !timeLineModelArrayList.isEmpty()) {

                            if (mDataList != null) {
                                mDataList.addAll(timeLineModelArrayList);
                            }

                        }

                        mTimeLineAdapter = new OrderProgrAdapter(//
                                RepairProgressTwoActivity.this,//
                                RepairProgressTwoActivity.this,//
                                (ArrayList<TimeLineModel>) mDataList);//

                        if (mTimeLineAdapter != null) {
                            mRecyclerView.setAdapter(mTimeLineAdapter);
                            mTimeLineAdapter.notifyDataSetChanged();
                        }

                        //这里也不用管是下拉刷新或者上拉加载更多，直接判断是否为空，
                        if (mDataList != null && mDataList.isEmpty()) {

                            //同时禁用加载更多；
//                            if (refreshLayoutInRepairManageListHistory != null) {
//                                refreshLayoutInRepairManageListHistory.setEnableLoadMore(false);
//                            }

                            fillNullDataView(StringUtils.getString(R.string.nulldatanow), R.drawable.errorsear);

                        }

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                        CommUtils.checkMaterialDialog(materialDialog);

                        if (apiException != null) {

                            if (!TextUtils.isEmpty(apiException.getDisplayMessage())) {
                                ToastUtils.showShort(apiException.getDisplayMessage());
                            }

                        }

                    }
                });

    }

    public void processExtraData() {

        Bundle bundle = this.getIntent().getExtras();

        if (bundle != null) {

            repairIdPass = bundle.getString(ExtraKey.EXTRA_PAYMENT_RECEIPTID);

        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        repairIdPass = "";

        if (mDataList != null && !mDataList.isEmpty()) {
            mDataList.clear();
            mDataList = null;//重置列表数据内容
        }

    }

    @Override
    protected void methodBack() {

        methodBackFinish();

    }
}